import { Effect, Reducer, history } from 'umi';
import { switchCompany } from '@/services/common';
import { setCookie } from '@/utils/cookie';
import { createAction } from '@/utils/common';
export interface ICommonState {
  activeCompany: any;
}

export interface ICommonModel {
  namespace: 'common';
  state: ICommonState;
  effects: {
    switchCompany: Effect;
  };
  reducers: {
    updateState: Reducer<ICommonModel>;
  };
}

const CommonModel: ICommonModel = {
  namespace: 'common',
  state: {
    activeCompany: {},
  },
  effects: {
    *switchCompany({ payload, callback }, { put, call }) {
      const activeCompany = yield call(switchCompany, { companyId: payload.id });
      localStorage.setItem('__cpy_curr', JSON.stringify(payload));
      setCookie('token', activeCompany?.token);
      setCookie('sid', activeCompany?.sid);
      setCookie('userId', activeCompany?.userId);
      setCookie('userName', activeCompany?.userName);
      callback?.();
      yield put(createAction('updateState')({ activeCompany: activeCompany || {} }));
      history.replace('/home');
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default CommonModel;
